﻿using System;
using System.Data.Entity;
using XHouse.Data.Interfaces;

namespace XHouse.Data
{
    /// <summary>
    /// The DatabaseFactory class is the proxy manager for all connections and transactions with the database.
    /// This class is responsible for the actual connection to the database. It holds the reference to the actual 
    /// database connection string from Web.Config.
    /// </summary>
    public class DatabaseFactory : Disposable, IDatabaseFactory
    {
        private XHouseDbContext db;

        /// <summary>
        /// Returns the active database object context instance or creates a new instance if one doesn't exist already.
        /// </summary>
        /// <returns>A XHouseDbContext object (which inherits from DbContext).</returns>
        public DbContext Get()
        {
            return db ?? (db = new XHouseDbContext("DefaultConnection"));
        }

        protected override void DisposeCore()
        {
            if (db != null)
                db.Dispose();
        }
    }

    /// <summary>
    /// The Disposable class is a managed disposable resource that can be explicitly called within other classes.
    /// </summary>
    public class Disposable : IDisposable
    {
        private bool isDisposed;

        ~Disposable()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
        private void Dispose(bool disposing)
        {
            if (!isDisposed && disposing)
            {
                DisposeCore();
            }

            isDisposed = true;
        }

        protected virtual void DisposeCore()
        {
        }
    }
}
